<template>
  <div class="m-2">
    <div
      v-for="(s, index) in switchList"
      :key="index"
      class="flex items-center space-x-2"
    >
      <div>{{ s.label }}</div>
      <el-switch
        v-model="s.value"
        :disabled="s.disabled"
        inline-prompt
        active-text="是"
        inactive-text="否"
        :loading="s.loading"
        :before-change="async () => handleChange(index)"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { getAppConfig, setCaptchaEn, setRegisterEn } from '@/api/app'
import { HttpResultCode } from '@/utils/http/enums'
import { onMounted, reactive, ref } from 'vue'
const switchList = reactive([
  {
    label: '允许注册',
    value: false,
    disabled: true,
    loading: false,
    fn: setRegisterEn
  },
  {
    label: '启用验证码',
    value: false,
    disabled: true,
    loading: false,
    fn: setCaptchaEn
  }
])
const handleChange = async (index: number): Promise<boolean> => {
  switchList[index].loading = true
  const { code } = await switchList[index].fn({
    enable: !switchList[index].value
  })
  switchList[index].loading = false
  return code === HttpResultCode.Success
}

onMounted(async () => {
  const { code, data } = await getAppConfig()
  if (code === HttpResultCode.Success) {
    switchList[0].value = data.register
    switchList[1].value = data.captcha
    switchList[0].disabled = false
    switchList[1].disabled = false
  }
})
</script>

<style scoped></style>
